package com.android.lovely.ui.fragment.role

import android.Manifest
import android.app.Activity
import android.net.Uri
import android.os.Build
import android.text.SpannableStringBuilder
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.android.lovely.R
import com.android.lovely.databinding.FragmentCreateRoleFourBinding
import com.android.lovely.databinding.FragmentCreateRoleOneBinding
import com.android.lovely.databinding.FragmentCreateRoleThreeBinding
import com.android.lovely.databinding.FragmentCreateRoleTwoBinding
import com.android.lovely.databinding.ItemKeyWordBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.ext.startImageCrop
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.BaseFragment
import com.android.lovely.framework.widget.FlexibleContentContainer
import com.android.lovely.room.role.CreateRole
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.android.lovely.ui.widget.CreateRoleBottomWidget.OnBottomClickListener
import com.android.lovely.ui.widget.CreateRoleTitleView.OnTitleClickListener
import com.android.lovely.ui.widget.RoleTipWidget
import com.android.lovely.user.UserManager
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.material.internal.ViewUtils.hideKeyboard
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.view.ViewExt.clickable
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/5 21:20
 */
class CreateRoleStep4Fragment : CreateRoleBaseFragment<FragmentCreateRoleFourBinding>() {


    private val styleText = "<START>\n{{user}}:\n{{char}}:"


    override fun initView() {
        mBinding.clBottom.update(viewModel.isEdit, object : OnBottomClickListener {
            override fun onPreview() {
                save()
                if (viewModel.isEdit) {
                    viewLifecycleOwner.lifecycleScope.launch {
                        viewModel.save()
                        activity?.finish()
                    }
                } else {
                    viewModel.nextStep(3)
                }
            }

            override fun onNext() {
                save()
                if (viewModel.isEdit) {
                    viewLifecycleOwner.lifecycleScope.launch {
                        viewModel.save()
                        activity?.finish()
                    }
                } else {
                    viewModel.nextStep(3)
                }
            }

            override fun onBack() {
                viewModel.preStep(3)
            }

        })

        getString(R.string._0_500_min_2, "0").also { mBinding.firstContentNum.text = it }
        getString(R.string._0_900_min_2, "0").also { mBinding.dialogueStyleContentNum.text = it }

        mBinding.firstContent.addTextChangedListener {
            getString(
                R.string._0_500_min_2,
                (it?.length.toString())
            ).also { mBinding.firstContentNum.text = it }
            checkEnable()
        }
        mBinding.dialogueStyleContent.addTextChangedListener {
            getString(
                R.string._0_900_min_2,
                (it?.length.toString())
            ).also { mBinding.dialogueStyleContentNum.text = it }
            checkEnable()
        }
        mBinding.addRounds.clickable {
            val text = mBinding.dialogueStyleContent.text ?: SpannableStringBuilder()
            if (900 - text.length < "\n\n${styleText}".length) {
                return@clickable
            }
            mBinding.dialogueStyleContent.requestFocus()
            if (text.isEmpty()) {
                text.insert(text.length, styleText)
            } else {
                text.insert(text.length, "\n\n${styleText}")
            }
            val selection = text.lastIndexOf("\n")
            if (selection >= 0) {
                runCatching {
                    mBinding.dialogueStyleContent.setSelection(selection)
                }
            }
            mBinding.nestedScrollView.post {
                mBinding.nestedScrollView.scrollTo(0, 0)
            }
        }
        mBinding.clTip.setListener(object : RoleTipWidget.OnClickListener {
            override fun onClick(text: String) {
                if (mBinding.firstContent.hasFocus()) {
                    mBinding.firstContent.text?.insert(
                        maxOf(mBinding.firstContent.selectionEnd, 0),
                        text
                    )
                }

                if (mBinding.dialogueStyleContent.hasFocus()) {
                    mBinding.dialogueStyleContent.text?.insert(
                        maxOf(
                            mBinding.dialogueStyleContent.selectionEnd,
                            0
                        ), text
                    )
                }
            }
        })
    }

    override fun update(it: CreateRole) {
        mBinding.firstContent.setText(it.firstMessage)
        mBinding.dialogueStyleContent.setText(it.chatExample)
        mBinding.clBottom.update(viewModel.isEdit)
        checkEnable()
    }

    private fun checkEnable() {
        var isEnable = true

        if ((mBinding.firstContent.text?.trim()?.length ?: 0) < 2) {
            isEnable = false
        }

        val styleLength = (mBinding.dialogueStyleContent.text?.trim()?.length ?: 0)
        if (styleLength != 0 && styleLength < 2) {
            isEnable = false
        }

        mBinding.clBottom.updateEnable(isEnable)
    }

    override fun save() {
        viewModel.updateRole {
            firstMessage = mBinding.firstContent.text.toString()
            chatExample = mBinding.dialogueStyleContent.text.toString()
        }
    }

    override fun hasEdit(): Boolean {
        return viewModel.createRole?.firstMessage != mBinding.firstContent.text.toString()
                || viewModel.createRole?.chatExample != mBinding.dialogueStyleContent.text.toString()
    }

    override fun onKeyBoardChange(progress: Int) {
        mBinding.clTip.updateLayoutParams<MarginLayoutParams> {
            bottomMargin = (progress - bottomHeight).coerceAtLeast(0)
        }
        mBinding.clTip.isVisible = progress > 0
    }

    override suspend fun initData() {

    }
}